package pl.edu.agh.mguesser.player;

import java.nio.file.Path;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import pl.edu.agh.mguesser.audioengine.AudioEngine;
import pl.edu.agh.mguesser.audioengine.AudioEngineException;
import pl.edu.agh.mguesser.audioengine.StreamInProgress;
import pl.edu.agh.mguesser.playlist.Playlist;

/**
 * @author keiran
 */
@Service
public class PlayerImpl implements Player {
    
    @Autowired
    private AudioEngine audioEngine;

    private Playlist playlist;
    
    private StreamInProgress streamInProgress;
    
    @Override
    public synchronized void play() throws PlayerException {
        if(streamInProgress != null) {
            throw new IllegalStateException();
        }
        
        try {
            streamInProgress = audioEngine.play(playlist.getCurrentSong());
            
        } catch (AudioEngineException ex) {
            throw new PlayerException(ex);
                    
        }
    }
    
    @Override
    public synchronized void stop() {
        if(streamInProgress == null) {
            return;
        }
        
        streamInProgress.stop();
        streamInProgress = null;
    }
    
    @Override
    public boolean hasNext() {
        return playlist.hasNext();
    }
    
    @Override
    public void next() {
        if(streamInProgress != null) {
            throw new IllegalStateException();
        }
        
        playlist.next();
    }

    @Override
    public Path getCurrent() {
        return playlist.getCurrentSong();
    }

    @Override
    public void setPlaylist(Playlist playlist) {
        if(streamInProgress != null) {
            throw new IllegalStateException();
        }
        
        this.playlist = playlist;
    }

    void setAudioEngine(AudioEngine audioEngine) {
        this.audioEngine = audioEngine;
    }

    StreamInProgress getStreamInProgress() {
        return streamInProgress;
    }
    
}
